 /**
 * @author caif
 * @fileoverview document router
 */
;(function(){
    App.Routers.appRouter = Backbone.Router.extend({
        template : tpl.breadcrumb, 
        
        routes: {
            "": "fetchList",
            "!home*path": "fetchList",
            "!public*path": "fetchPublic",
            "!myProject*path": "fetchProjectItemList",
            "!recycle*path": "fetchRecycle",
            "!share/shareForMe*path": "fetchShareListForMe",
            "!share/shareByMe*path": "fetchShareListByMe",
            "!databag/:name/:id/:type/*path": "getDatabag"
        },
        
        initialize : function(){
            var self = this;
            self.docList = $('#document_list');
            self.refreshIcon = $("#icon-refresh").click(function(){
            	self.appView.clearDataWhileRefresh();
            	Backbone.history.loadUrl(window.location.hash);
                return false;
            });
            self.ajaxLoadingIcon = $("#icon-ajax-loading");
            self.loadCover = $('#loading-cover');
            self.documentView = $('#document_viewer');
            self.projectView = $('#mod-project-view');
            self.leftSider = $('#sider');
            self.appView = App.viewInstances.appView;
        },
        
        fetchList: function(path) {
            var self = this;
            self.activeLeftMenu($('#' + App.util.getIdWithPrefix(self.appView.leftMenuIds.ownMe)));
            self.loadShow();
            self.appView.currentFilter = {
                fromOwnMe: true,
                rootPath: '#!home',
                parentId: App.util.getParaValue('id', path) || ''
            }
            var queryStr = self.getQueryStrByPath(path);
            var id = App.util.getParaValue('id', path);
            self.appView.itemCollection.fetch({
                url: id ? App.util.contextPath + "/file/"+id+".json?" + queryStr+"&child&path" : App.util.contextPath + "/file.json?" +"personal&path",
                fromOwnMe: true,
                success: function(collection, response, options){
                    self.loadHide();
                    self.initRowHeader();
                    self.dealBreadcrumb(App.i18n.get('fromOwnMe'), response.path, {fromOwnMe: true});
                }
            });
        },
        
        fetchPublic: function(path){
            var self = this;
            self.activeLeftMenu($('#' + App.util.getIdWithPrefix(self.appView.leftMenuIds.publicMe)));
            self.loadShow();
            var queryStr = self.getQueryStrByPath(path);
            self.appView.currentFilter = {
                fromPublic: true,
                rootPath: '#!public'
            }
            self.appView.itemCollection.fetch({
                url: App.util.contextPath + "/share/listPublic.json?" + queryStr,
                success: function(collection, response, options){
                    self.loadHide();
                    self.initRowHeader();
                    self.dealBreadcrumb(App.i18n.get('publicDoc'), response.path, {fromPublic: true});
                }
            });
        },
        
        fetchProjectList: function(path, activeMenu){
        	//list all projects
            var self = this;
            if(self.appView.allProjectPanel.data('data-loaded')){
            	if(self.appView.projectCollection.length > 0){
            	   self.appView.projectList.slideDown();
            	}else{
            	   self.appView.noProjectTip.slideDown();
            	}
                self.appView.allProjectPanel.addClass('toggle-panel-expand');
                return;
            }
            self.appView.allProjectPanel.data('data-loaded', true);
            $('#loading-projectlist-tip').show();
            var id = App.util.getParaValue('id', path);
            self.appView.currentFilter = {
                fromProjectList: true,
                rootPath: '#!myProject',
                parentId: id
            }
            self.appView.projectCollection.fetch({
                url: App.util.contextPath + '/file?project&path',
                fromProjectList: true,
                activeMenu: activeMenu,
                success: function(collection, response, options){
                	//todo
                }
            });
        },
        
        fetchProjectItemList: function(path){
        	//list project's files and folders
            var self = this,
            queryStr,
            id = App.util.getParaValue('id', path);
            self.fetchProjectList(path, true);
            self.loadShow();
            self.appView.currentFilter = {
                fromProject: true,
                rootPath: '#!myProject',
                parentId: id
            }
            self.appView.itemCollection.fetch({
                url: App.util.contextPath + '/file/' + id + '?child&path',
                fromProject: true,
                success: function(collection, response, options){
                    self.loadHide();
                    self.appView.updateHeaderBtn();
                    self.dealBreadcrumb(null, response.path, {fromProject: true});
                    self.activeProjectMenu(true);
                }
            });
        },
        
        staticFetchItems: function(id, projectId, callback){
            var self = this;
            $.ajax({
                url: App.util.contextPath + '/file/' + id + '.json?child',
                success: function(data){
            	   callback && callback(data.items, id, projectId);
                }
            });
        },
        
        fetchShareListByMe: function( path ) {
            var self = this;
            self.activeLeftMenu($('#' + App.util.getIdWithPrefix(self.appView.leftMenuIds.shareByMe)));
            self.loadShow();
            var queryStr = self.getQueryStrByPath(path) + '&root=' + $("#rootFileId").val();
            self.appView.currentFilter = {
                fromFilesByMe: true,
                rootPath: '#!share/shareByMe'
            }
            self.appView.itemCollection.fetch({
                url: App.util.contextPath + "/share/listByMe.json?" + queryStr,
                success : function(collection, response, options){
                    self.loadHide();
                    self.initRowHeader();
                    self.dealBreadcrumb(App.i18n.get('shareByMe'), response.path, {fromFilesByMe: true});
                }
            });
        },
        
        fetchShareListForMe: function( path ) {
            var self = this;
            self.activeLeftMenu($('#' + App.util.getIdWithPrefix(self.appView.leftMenuIds.shareForMe)));
            self.loadShow();
            var queryStr = self.getQueryStrByPath(path);
            self.appView.currentFilter = {
                fromFilesForMe: true,
                rootPath: '#!share/shareForMe'
            }
            self.appView.itemCollection.fetch({
                url: App.util.contextPath + "/share/listForMe.json?" + queryStr, 
                success : function(collection, response, options){
                    self.loadHide();
                    self.initRowHeader(true);
                    self.dealBreadcrumb(App.i18n.get('shareForMe'), response.path, {fromFilesForMe: true});
                }
            });
        },
        
        fetchRecycle : function( path ){
            var self = this;
            self.activeLeftMenu($('#' + App.util.getIdWithPrefix(self.appView.leftMenuIds.recycleMe)));
            self.loadShow();
            var queryStr = self.getQueryStrByPath(path);
            self.appView.currentFilter = {
                fromRecycle: true,
                rootPath: '#!recycle'
            }
            self.appView.itemCollection.fetch({
                url: App.util.contextPath + "/recycler.json",
                success : function(collection, response, options){
                    self.loadHide();
                    self.initRowHeader();
                    self.dealBreadcrumb(App.i18n.get('recycle'), response.path, {fromRecycle: true});
                },
                fromRecycle: true
            });
        },
        
        loadShow : function(){
            var self = this;
            self.refreshIcon.css('display', 'none');
            self.ajaxLoadingIcon.show();
            self.loadCover.show();
            $("#databag-iframe").hide();
            $("#glodon_container,#search_form").show();
            
            return self;
        },
        
        loadHide : function(){
            var self = this;
            self.refreshIcon.css('display', 'inline-block');
            self.ajaxLoadingIcon.hide();
            self.loadCover.hide();
            self.appView.hideDetailPanel();
            return self;
        },
        
        initRowHeader: function(hasOwnerRow){
            var self = this,
            hash = location.hash,
            id = App.util.getParaValue('id', hash),
            orderType = App.util.getParaValue('orderType', hash);
            if(id === undefined){
                id = '';
            }
            $('#orderheader-wrap a').attr('href', function(){
                var t = $(this),
                orderBy = t.attr('htype'),
                href = '';
                href = 'id=' + id + '&orderBy=' + orderBy + '&orderType=' + (orderType === '1' ? '-1' : '1');
                return (hash ? (hash.split('&')[0] + '&') : '#!home&') + href;
            });
            var currentOrderBy = App.util.getParaValue('orderBy', hash);
            $('#orderheader-wrap .orderheader').removeClass('ordertype-down ordertype-up');
            if(currentOrderBy){
                //add icon to header row
                var cls = 'up';
                if(orderType === '-1'){
                    cls = 'down';
                }
                var target = $('#' + currentOrderBy).addClass('ordertype-' + cls),
                cloneA = target.find('a').clone();
                $('#thumbnail-view-sort .current').empty().append(cloneA).removeClass('ordertype-down ordertype-up').addClass('ordertype-' + cls);
            }
            $('#document_content')[hasOwnerRow ? 'addClass' : 'removeClass']('has-owner-list');
            self.selectPreActionItem(id);
        },
        
        selectPreActionItem: function(id){
            var self = this,
            ls = store.get('glodon_storage') || {};
            if(ls.prevId){
                var children = self.docList.children();
                $.each(children, function(idx, item){
                    var view = $(item).data('view');
                    if(view && view.model.get('id') === ls.prevId){
                        $(item).addClass('highlight');
                        self.docList.animate({'scrollTop': $(item)[0].offsetTop}, 0);
                        return false;
                    }
                });
            }else{
                self.docList.animate({'scrollTop': 0}, 0);
            }
            ls.prevId = id;
            store.set('glodon_storage', ls);
            self.appView.updateHeaderBtn();
        },
        /**
         * @description get databag prototype
         * @param {String} path path URL hash  
        */
        getDatabag : function( name , databagId , type , path){
            $("#fnav >li").hide();
            $(".databag_return").show();
            $(".view_model, .search_model").hide();
            
            if(type=="rvt" || type=="dwg")
            {
                $("#glodon_container").hide();
            }
            
            $("#databag-iframe").html("<iframe class='databag-flag' id='dataImage' data-back="+path+" dataBagId="+databagId+" frameborder=0 width=100% height=100% filename=" +  name + " scrolling=no src='"+window._global.databagURL+"/page/"+type+"'></iframe>").show(); 
        },
        
        dealBreadcrumb: function(startName, navigation, otherData){
            var self = this;
            self.appView.breadcrumbCollection.reset();
            if(_.isString(startName)){
                self.appView.breadcrumbCollection.add( new App.Models.breadcrumbModel(_.extend({name: startName}, otherData)) );
            }
            if( navigation !== "/" && _.isArray( navigation )){  
                $("#rootFileId").val(navigation[0].id);
                for( var i=0 ; i< navigation.length ; i++){
                    self.appView.breadcrumbCollection.add(new App.Models.breadcrumbModel(_.extend(navigation[i], otherData)));
                }
            }else{
                $("#rootFileId").val("");
            }
            return self;
        },
        
        activeLeftMenu: function(menu){
            var self = this;
            self.leftSider.find('.active').removeClass('active');
            menu.addClass('active');
            while(menu.parent().parent().is('.nav-list-item')){
                var parentUL = menu.parent().slideDown();
                var model = self.appView.getProjectItemModelById(parentUL.parent().attr('id'));
                model.set('uiOpen', true);
                menu = menu.parent().parent();
            }
        },
        
        activeProjectMenu: function(fetchData){
            var self = this;
            if(!self.appView.isProjectListInsertToDOM) return;
            var hash = window.location.hash,
            id = App.util.getParaValue('id', hash);
            var targetMenu = $('#' + App.util.getIdWithPrefix(id));
            if(targetMenu.length > 0){
                //menu exist
                self.activeLeftMenu(targetMenu);
            }else if(fetchData){
                //menu not exist, get full path
                (new App.Collections.ItemCollection()).fetch({
                    url: App.util.contextPath + '/file/' + id + '?tree',
                    success: function(collection, options){
                        var data = collection.at(0).toJSON();
                        self.appView.expandProjectListByData([data], function(){
                            self.activeProjectMenu(false);
                        });
                    }
                });
            }
        },
        
        getQueryStrByPath: function(path){
            var self = this,
            id = App.util.getParaValue('id', path),
            orderBy = App.util.getParaValue('orderBy', path),
            orderType = App.util.getParaValue('orderType', path);
            var queryStr = '';
            if(id === undefined){
                queryStr += 'id=';
            }else{
                queryStr += 'id=' + id;
            }
            if(orderBy){
                queryStr += '&orderBy=' + orderBy;
            }
            if(orderType){
                queryStr += '&orderType=' + orderType;
            }
            return queryStr;
        }
    });
    $(function(){
        App.initialize( "appRouter" , true );
    });
})();
